package cn.hsa.fqz.task.service.impl;

import cn.hsa.fqz.task.service.IDataFluxService;
import cn.hsa.fqz.task.service.TjtcAlgorithmService;
import cn.hsa.fqz.task.service.dto.RecordDTO;
import cn.hsa.fqz.task.service.dto.RecordDetailsDTO;
import cn.hsa.fqz.util.DataUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @date 2023-07-18 10:45
 */

@Slf4j
@Service
public class TjtcAlgorithmServiceImpl implements TjtcAlgorithmService {

    @Autowired
    private IDataFluxService dataFluxService;

    @Override
    public Integer algorithNonTjtcWithZY(String host,Integer port,String passwd,String prv, String sourceTableName, String targetTableName, String detailTableName, String subType) {
        return null;
    }

    @Override
    public Integer algorithTjtcWithZY(String host,Integer port,String passwd,String prv, String sourceTableName, String targetTableName, String detailTableName) {
        try {
            String sql = "select certno,thzjhm,psn_name,thxm,fixmedins_name,prv,start_date,end_date,dscg_maindiag_code,thjb,medfee_sumamt," +
                    "thzje,fixmedins_code,mdtrt_id,fund_pay_sumamt,thbxje,thzyid" +
                    " from "+sourceTableName+" where prv = '"+prv+"'";
            System.out.println("query语句: "+ sql);
            List<Map<String, Object>> sqlData = dataFluxService.getTaskSqlExecuteList(host,port,passwd, sql);
            List<RecordDTO> ls = Lists.newArrayList();
            Map<String,Integer> mmp = Maps.newHashMap();
            Integer countrow = 1;
            System.out.println("算法模型启动开始......");
            if(CollectionUtil.isNotEmpty(sqlData)){
                for (Map<String,Object> rs:sqlData) {
                    RecordDTO record = new RecordDTO();
                    String beginTime = String.valueOf(rs.get("start_date")).substring(0,10);
                    String endTime = String.valueOf(rs.get("end_date")).substring(0, 10);
                    record.setSubjCertNo(String.valueOf(rs.get("certno")));
                    record.setObjCertNo(String.valueOf(rs.get("thzjhm")));
                    record.setSubjName(String.valueOf(rs.get("psn_name")));
                    record.setObjName(String.valueOf(rs.get("thxm")));
                    record.setFixmedinsName(String.valueOf(rs.get("fixmedins_name")));
                    record.setFixmedinsCode(String.valueOf(rs.get("fixmedins_code")));
                    record.setMdtrtId(String.valueOf(rs.get("mdtrt_id")));
                    record.setFundPaySumamt(String.valueOf(rs.get("fund_pay_sumamt")));
                    record.setPrv(String.valueOf(rs.get("prv")));
                    record.setSubjJb(String.valueOf(rs.get("dscg_maindiag_code")));
                    record.setObjJb(String.valueOf(rs.get("thjb")));
                    record.setSubje(String.valueOf(rs.get("medfee_sumamt")));
                    record.setObjJe(String.valueOf(rs.get("thzje")));
                    record.setBgTime(beginTime);
                    record.setEdTime(endTime);
                    record.setThbxje(String.valueOf(rs.get("thbxje")));
                    record.setThzyid(String.valueOf(rs.get("thzyid")));
                    record.setKey(String.valueOf(rs.get("fixmedins_name")+beginTime+endTime));
                    if(mmp.get(String.valueOf(rs.get("certno"))) == null){
                        mmp.put(String.valueOf(rs.get("certno")), countrow);
                        countrow++;
                    }
                    if(mmp.get(String.valueOf(rs.get("thzjhm")))==null){
                        mmp.put(String.valueOf(rs.get("thzjhm")), countrow);
                        countrow++;
                    }
                    ls.add(record);
                }
            }
            String insertSql = "insert into "+targetTableName+"(thxq,count_num,fixmedins_code,fixmedins_name,bg_time,ed_time,weight,thnamexq,prv,jb,`type`,sub_type) " +
                    "values('%s',%s,'%s','%s','%s','%s','%s','%s','%s','%s','1','1')";
            Map<String,List<RecordDTO>> map = ls.stream().collect(Collectors.groupingBy(RecordDTO::getKey));
            for (Map.Entry<String,List<RecordDTO>> entry: map.entrySet()) {
                List<RecordDTO> list = entry.getValue();

                Set<String> set = new HashSet<String>();
                Set<String> set1 = new HashSet<>();
                Set<String> set2 = new HashSet<String>();

                set.add(list.get(0).getSubjCertNo());
                set.add(list.get(0).getObjCertNo());
                for (RecordDTO r : list) {
                    if(set.contains(r.getSubjCertNo())||set.contains(r.getObjCertNo())){
                        set.add(r.getSubjCertNo());
                        set.add(r.getObjCertNo());

                        set1.add(r.getSubjName());
                        set1.add(r.getObjName());

                        set2.add(r.getSubjJb());
                        set2.add(r.getObjJb());
                    }
                }
                String data = DataUtils.genSetString(set);
                String nameData = DataUtils.genSetString(set1);
                String jbData = DataUtils.genSetString(set2);
                String key = DigestUtils.md5Hex(data+"11");
                List<RecordDetailsDTO> details = Lists.newArrayList();
                for (RecordDTO r : list) {
                    RecordDetailsDTO subj = new RecordDetailsDTO();
                    subj.setFixmedinsName(r.getFixmedinsName());
                    subj.setBgTime(r.getBgTime());
                    subj.setEdTime(r.getEdTime());
                    subj.setJb(DataUtils.stringIsEmpty(r.getSubjJb())?"":r.getSubjJb());
                    subj.setName(r.getSubjName());
                    subj.setCertno(r.getSubjCertNo());
                    subj.setJe(r.getSubje());
                    subj.setPrv(prv);
                    subj.setKey(key);
                    subj.setFixmedinsCode(r.getFixmedinsCode());
                    subj.setMdtrtId(r.getMdtrtId());
                    subj.setFundPaySumamt(r.getFundPaySumamt());
                    if(!DataUtils.isInList(details,subj)){
                        details.add(subj);
                    }
                    RecordDetailsDTO obj = new RecordDetailsDTO();
                    obj.setFixmedinsName(r.getFixmedinsName());
                    obj.setBgTime(r.getBgTime());
                    obj.setEdTime(r.getEdTime());
                    obj.setJb(DataUtils.stringIsEmpty(r.getObjJb())?"":r.getObjJb());
                    obj.setName(r.getObjName());
                    obj.setCertno(r.getObjCertNo());
                    obj.setJe(r.getObjJe());
                    obj.setPrv(prv);
                    obj.setKey(key);
                    obj.setFixmedinsCode(r.getFixmedinsCode());
                    obj.setMdtrtId(r.getThzyid());
                    obj.setFundPaySumamt(r.getThbxje());
                    if(!DataUtils.isInList(details,obj)){
                        details.add(obj);
                    }
                }
                String finalSql = String.format(insertSql,data,set.size(),list.get(0).getFixmedinsCode(),list.get(0).getFixmedinsName(),list.get(0).getBgTime(),list.get(0).getEdTime(),
                key,nameData,list.get(0).getPrv(),jbData);
                dataFluxService.executeSql(host, port,passwd, finalSql);
                String insertDetailSql = "insert into "+detailTableName+"(prv,psn_name,certno,fixmedins_name,start_date," +
                        "end_date,dscg_maindiag_code,medfee_sumamt,fixmedins_code,mdtrt_id,fund_pay_sumamt,group_key,`type`,sub_type) " +
                        "values('%s',%s,'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','1','1')";
                System.out.println("数据详情大小: " + details.size());
                for (RecordDetailsDTO rd: details) {
                    if(set.contains(rd.getCertno())){
                        String finalDSql = String.format(insertDetailSql,rd.getPrv(),rd.getName(),rd.getCertno(),rd.getBgTime(),rd.getEdTime(),
                                rd.getJb(),rd.getJe(),rd.getFixmedinsCode(),rd.getMdtrtId(),rd.getFundPaySumamt(),rd.getKey());
                        dataFluxService.executeSql(host,port,passwd, finalDSql);
                    }
                }
            }
            System.out.println(JSON.toJSONString(mmp));
            System.out.println("算法模型执行完毕.....");
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }
}
